/**
 *  此组件为自定义lottie动画库，后续可参考官网自行增加动画和优化
 */
import lottie from 'lottie-miniprogram';
var inited = null;
var ani = null;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    //组件唯一标识id;定义格式: 当前路由的后缀名 + lottie动画名 + '_'+正整数 (必须传)
    canvasId: {
      type: String,
      value: ''
    },
    //lottie 动画效果名称  (必须传)
    name: {
      type: String,
      value: '',
    },
    //相关描述文字
    desc: {
      value: String,
      value: ''
    },
    //是否循环,该属性部分机型会出现提示：小程序运行内存不足，请重新打开的问题；建议不开启
    loop: {
      type: Boolean,
      value: false
    },
    //是否自动播放
    autoplay: {
      type: Boolean,
      value: true
    },
    width: {
      type: String,
      value: '300px'
    },
    height: {
      type: String,
      value: '300px'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    animationStatus: true,
    isLottieAnimation: true, //是否为lottie动画
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 加载lottie动画
     * @param {*} name lottie 动画名称
     * @param {*} config loop:是否循环播放  autoplay:是否自动播放
     * @param {*} width 
     * @param {*} height 
     */
    loadLottieAnimation(name, config = {
      loop: true,
      autoplay: true
    },
      width = '300px', height = '300px') {
      if (this.inited) {
        return
      }
      wx.createSelectorQuery().in(this).select(`#${this.properties.canvasId}`).node(res => {
        if (res) {
          const canvas = res.node;
          const context = canvas.getContext('2d');
          canvas.width = Number(width.match(/[0-9]/g).join(''));
          canvas.height = Number(height.match(/[0-9]/g).join(''));
          lottie.setup(canvas);
          //加载lottie数据
          // require.async(`@lottie/${name}.js`).then(pkg => {
          require.async(`../../utils/lottieJson/${name}.js`).then(pkg => {
            this.ani = lottie.loadAnimation(Object.assign({
              animationData: pkg,
              rendererSettings: {
                context,
              },
            }, config));
            this.inited = true
          }).catch(err => {
            console.log(err);
            //防止加载不出lottie数据
            this.setData({
              isLottieAnimation: false
            })
          })
        } else {
          this.setData({
            isLottieAnimation: false
          })
        }

      }).exec()
    },
    /**
     * 暂停lottie动画
     */
    pauseAnimation() {
      this.ani.pause();
    },
    /**
     * 继续播放lottie动画
     */
    playAnimation() {
      this.ani.play();
    },
    changeAnimationStatus() {
      this.setData({
        animationStatus: !this.data.animationStatus
      })
      this.data.animationStatus ? this.pauseAnimation() : this.playAnimation();
    },
  },
  lifetimes: {
    ready() {
      this.loadLottieAnimation(this.properties.name, {
        loop: this.properties.loop,
        autoplay: this.properties.autoplay
      });
    },
    detached() {
      this.setData({
        isLottieAnimation: false
      })
      this.ani = null;
    }
  }
})